package netty.groupChat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ
 * Author:熊磊
 */
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String > {
    //使用一个hashmap管理
    //public static Map<String,Channel> channels= new HashMap<>();
    //channels.put("id",channel)
    //channels.get("id").writeAndFlush(msg) 实现私聊 and 点对点聊天

    //GlobalEventExecutor.INSTANCE 是一个全局的事件执行器
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    //当连接建立时调用该方法
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        // 将该客户加入聊天的信息推送给其他在线的客户端
        /**
         * 遍历channelGroup 发送信息
         */
        channelGroup.writeAndFlush(sdf.format(new Date())+": [客户端]"+channel.remoteAddress()+"加入聊天\n");
        channelGroup.add(channel);
    }


    /**
     * channelGroup会自动remove 离开的channel
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush(sdf.format(new Date())+": [客户端]"+channel.remoteAddress()+"离开了\n");
        System.out.println(channelGroup.size());
    }

    // 表示channel 处于活动状态,提示xx上线
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(sdf.format(new Date())+": "+ctx.channel().remoteAddress()+"上线了");
    }
    //不活动状态
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(sdf.format(new Date())+": "+ctx.channel().remoteAddress()+"离线了");
    }

    //读取数据
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        //获取到当前的channel
        Channel channel = ctx.channel();

        channelGroup.forEach(ch ->{
            if (channel!=ch){
                ch.writeAndFlush(sdf.format(new Date())+": [客户]"+channel.remoteAddress()+"发送了消息"+msg+"\n");
            }else {
                System.out.println(sdf.format(new Date())+": [客户]"+channel.remoteAddress()+"发送了消息"+msg);
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
